package com.hf.order

import java.text.MessageFormat

import com.hf.constant.OrderLunchConst
import com.hf.date.DateUtils
import com.hf.fetch.UserFetchSummary
import com.hf.fetch.UserFetchSummaryService
import com.hf.mail.AbstractMailService
import com.hf.mail.MailMessage
import com.hf.mail.MailSenderService
import com.hf.security.OrderUser
import com.hf.security.OrderUserService
import com.hf.security.ValidCode
import com.hf.security.ValidCodeService
import com.hf.template.GspTemplateUtils

class MailOrderService extends AbstractMailService {

	ValidCodeService validCodeService
	OrderUserService orderUserService
	UserFetchSummaryService UserFetchSummaryService

	void sendMail() {
		List<UserFetchSummary> fetchUserSummaryList = UserFetchSummaryService.getUserFetchSummarySortList(orderUserService.availableUserList)

		ValidCode validCode
		List orderLinkList = []
		String settingLink
		String registerLink

		String serverHome1 = MessageFormat.format(OrderLunchConst.SERVER_HOME_FORMAT,OrderLunchConst.SERVER_DOMAIN1)
		String serverHome2 = MessageFormat.format(OrderLunchConst.SERVER_HOME_FORMAT,OrderLunchConst.SERVER_DOMAIN2)
		String serverHome3 = MessageFormat.format(OrderLunchConst.SERVER_HOME_FORMAT,OrderLunchConst.SERVER_IP)
		MailMessage mail = new MailMessage()
		mail.subject = OrderLunchConst.FROM_ORDER_LUNCH + "Order lunch?   " + DateUtils.todayInfo

		String fetchHtml = GspTemplateUtils.renderTemplate('/fetch/emailFetchList', [fetchUserSummaryList: fetchUserSummaryList])

		for (UserFetchSummary userFetchSummary : fetchUserSummaryList) {
			OrderUser user = userFetchSummary.user
			if(OrderLunchConst.IS_TEST && user.name != OrderLunchConst.ADMIN_NAME) {
				continue;
			}
			ValidCode.withNewTransaction {
				validCode = validCodeService.getValidCode(user.email)
			}
			orderLinkList[0] = "$serverHome1/userOrderHistory/orderFromEmail?userId=$user.id&code=$validCode.code"
			orderLinkList[1] = "$serverHome2/userOrderHistory/orderFromEmail?userId=$user.id&code=$validCode.code"
			orderLinkList[2] = "$serverHome3/userOrderHistory/orderFromEmail?userId=$user.id&code=$validCode.code"

			settingLink = "$serverHome1/orderUser/orderSettingFromMail?userId=$user.id&code=$validCode.code"
			
			registerLink = "$serverHome1/orderUser/register"

			send(mail, user, orderLinkList, settingLink, registerLink, fetchHtml)
		}
		log.info "Sent to: $fetchUserSummaryList.size persons"
	}

	private void send(MailMessage mail, OrderUser user, List orderLinkList, String settingLink, String registerLink, String fetchHtml) {
		mail.to = [user.email]
		mail.htmlText = GspTemplateUtils.renderTemplate('/order/user/emailOrderLunch',[orderLinkList:orderLinkList, settingLink: settingLink, registerLink:registerLink, fetchHtml:fetchHtml])

		mailSenderService.sendAsyn(mail)
	}
}
